import os
import uuid
from datetime import datetime
from typing import List, Optional
from fastapi import UploadFile, HTTPException, Request
import aiofiles
from PIL import Image
import io

class UploadService:
    def __init__(self):
        # 配置上传目录
        self.upload_dir = "static/uploads"
        self.allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.webp'}
        self.max_file_size = 10 * 1024 * 1024  # 10MB
        
        # 确保上传目录存在
        os.makedirs(self.upload_dir, exist_ok=True)
    
    async def upload_single_image(self, file: UploadFile, request: Request) -> dict:
        """上传单个图片"""
        try:
            # 验证文件类型
            if not self._is_valid_file(file):
                raise HTTPException(status_code=400, detail="不支持的文件类型")
            
            # 验证文件大小
            if file.size and file.size > self.max_file_size:
                raise HTTPException(status_code=400, detail="文件大小超过限制")
            
            # 生成唯一文件名
            file_extension = os.path.splitext(file.filename)[1].lower()
            unique_filename = f"{uuid.uuid4().hex}{file_extension}"
            
            # 按日期创建子目录
            date_path = datetime.now().strftime("%Y/%m/%d")
            upload_path = os.path.join(self.upload_dir, date_path)
            os.makedirs(upload_path, exist_ok=True)
            
            # 完整文件路径
            file_path = os.path.join(upload_path, unique_filename)
            
            # 保存文件
            async with aiofiles.open(file_path, 'wb') as f:
                content = await file.read()
                await f.write(content)
            
            # 生成完整的网络访问URL
            base_url = str(request.base_url).rstrip('/')
            file_url = f"{base_url}/static/uploads/{date_path}/{unique_filename}"
            
            return {
                "success": True,
                "filename": unique_filename,
                "original_name": file.filename,
                "file_url": file_url,
                "file_size": len(content),
                "upload_time": datetime.now().isoformat()
            }
            
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"上传失败: {str(e)}")
    
    async def upload_multiple_images(self, files: List[UploadFile], request: Request) -> dict:
        """上传多个图片"""
        results = []
        for file in files:
            try:
                result = await self.upload_single_image(file, request)
                results.append(result)
            except Exception as e:
                results.append({
                    "success": False,
                    "filename": file.filename,
                    "error": str(e)
                })
        
        return {
            "success": True,
            "total": len(files),
            "successful": len([r for r in results if r.get("success", False)]),
            "failed": len([r for r in results if not r.get("success", False)]),
            "files": results
        }
    
    def _is_valid_file(self, file: UploadFile) -> bool:
        """验证文件类型"""
        if not file.filename:
            return False
        
        file_extension = os.path.splitext(file.filename)[1].lower()
        return file_extension in self.allowed_extensions
    
    async def delete_image(self, file_url: str) -> bool:
        """删除图片"""
        try:
            # 从URL中提取文件路径
            if file_url.startswith('/static/'):
                file_path = file_url.replace('/static/', 'static/')
            else:
                file_path = file_url
            
            if os.path.exists(file_path):
                os.remove(file_path)
                return True
            return False
        except Exception as e:
            print(f"删除文件失败: {e}")
            return False 